package com.sky.service.impl;


import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.OrderService;
import com.sky.service.ReportService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderService orderService;

    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnOverStstistics(LocalDate begin, LocalDate end) {
        //将每天的日期封装到list集合中
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        log.info("日期:{}", dateList);

        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);

            //查询每天的营业额
            Map map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
            Double amount = orderMapper.getSumAmount(map);
            amount = amount == null ? 0.0 : amount;
            turnoverList.add(amount);
        }
        log.info("营业额:{}", turnoverList);


        //封装vo对象并返回
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }


    /**
     * 用户统计
     *
     * @param begin
     * @param end
     * @return
     */

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        // 将日期集合转换成字符串
        String dateli = StringUtils.join(dateList, ",");

        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);

            // 查询每天新增用户数量
            Integer newUserCount = userMapper.getNewUserCount(endTime, beginTime);
            newUserList.add(newUserCount);

            // 查询每天总用户数量
            Integer totalUserCount = userMapper.gettotalUserCount(beginTime);
            totalUserList.add(totalUserCount);

        }

        // 封装VO对象并返回 封装vo对象并返回
        return UserReportVO.builder()
                .dateList(dateli)
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();

    }

    //订单统计

    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        // 将日期集合转换成字符串
        String dateli = StringUtils.join(dateList, ",");

        // 订单总数
        List<Integer> orderCompletionRateList = new ArrayList<>();
        // 有效订单总数
        List<Integer> validOrderCountList = new ArrayList<>();
        //订单数列表
        List<String> OrderList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);

            //查询每天订单总数
            Integer totalOrderCount = orderMapper.getOrderCount(beginTime, endTime);
            orderCompletionRateList.add(totalOrderCount);

            // 查询每天有效订单总数
            Map m = new HashMap<>();
            m.put("begin", beginTime);
            m.put("end", endTime);
            m.put("status", Orders.COMPLETED);
            Integer validOrderCount = orderMapper.getValidOrderCount(m);
            validOrderCountList.add(validOrderCount);


        }
        //时间区间内的总订单数
        Integer totalOrderCount = orderCompletionRateList.stream().reduce(Integer::sum).get();
        //时间区间内的总有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }

        // 封装VO对象并返回 封装vo对象并返回
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCompletionRateList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 销量排名top10
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getBytime(beginTime, endTime);

        String nameList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList()), ",");
        String numberList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()), ",");

        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();

    }

    @Override
    public void export(HttpServletResponse response) {
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        //获取新增用户
        Integer userCount = userMapper.getNewUserCount(beginTime, endTime);

        //有效订单数
        Map map = new HashMap<>();
        map.put("begin", beginTime);
        map.put("end", endTime);
        map.put("status", Orders.COMPLETED);
        Integer orderCount = orderMapper.getValidOrderCount(map);

        //获得总订单数
        Integer totalCount=orderMapper.getOrderCount(beginTime, endTime);

        //订单完成率
        double l=0;
        if(totalCount!=0){
            l=orderCount/totalCount;
        }

        //营业额
        Double d=orderMapper.getSumAmount(map);
        d=d==null?0:d;

        //平均客单价
        double price=0;
        if(orderCount!=0){
            price=d/orderCount;
        }

        //获得一个输入流
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("运营数据报表模板.xlsx");

        try {
            // 创建一个excel对象
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            // 获取第一个sheet
            XSSFSheet sheet = excel.getSheetAt(0);
            //
            sheet.getRow(1).getCell(1).setCellValue(begin+"至"+end);
            // 获取第4行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(d);
            row.getCell(4).setCellValue(l);
            row.getCell(6).setCellValue(userCount);
            // 获取第5行
             row = sheet.getRow(4);
             row.getCell(2).setCellValue(orderCount);
             row.getCell(4).setCellValue(price);

            for (int i = 0; i < 30; i++) {//getBusinessData
                LocalDate dateBegin = begin.plusDays(i);
                BusinessDataVO businessData = orderService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MAX), LocalDateTime.of(dateBegin, LocalTime.MIN));
                //获取第？行
                 row = sheet.getRow(7 + i);
                 row.getCell(1).setCellValue(dateBegin.toString());
                 row.getCell(2).setCellValue(businessData.getTurnover()); //营业额
                 row.getCell(3).setCellValue(businessData.getValidOrderCount()); //有效订单数
                 row.getCell(4).setCellValue(businessData.getOrderCompletionRate()); //订单完成率
                 row.getCell(5).setCellValue(businessData.getUnitPrice()); //平均客单价
                 row.getCell(6).setCellValue(businessData.getNewUsers());

            }

            //通过输出流将文件下载到客户端浏览器中
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.flush();
            out.close();
            excel.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

}


